<template>
  <view class="container">
    <!-- 悬浮发布按钮 -->
    <view class="publish-btn" v-if="!showPublish" @tap="showPublishModal">
      <image src="@/static/images/icon/publish.png" class="publish-icon" />
    </view>

    <!-- 内容列表 -->
    <view class="content-list">
      <view v-for="(item, index) in contentList" :key="index" class="content-item">
        <view class="user-info">
          <image :src="item.userAvatar" class="avatar" />
          <text class="username">{{ item.username }}</text>
        </view>
        
        <view class="content-main">
          <text class="content-text">{{ item.content }}</text>
          <!-- 显示话题标签 -->
          <text v-if="item.topic" class="topic-tag">{{ item.topic }}</text>
          <view v-if="item.mediaUrl && isImage(item.mediaUrl)" class="image-list">
            <image 
              :src="item.mediaUrl" 
              class="content-image"
              mode="aspectFill"
              @tap="previewImage([item.mediaUrl], 0)"
            />
          </view>
          <video 
            v-if="item.mediaUrl && isVideo(item.mediaUrl)" 
            :src="item.mediaUrl" 
            class="content-video"
            controls
          ></video>
        </view>

        <view class="content-footer">
          <view class="interaction">
            <view class="like" @tap="handleLike(item)" :class="{ 'like-animating': item.likeAnimating }">
              <image 
                :src="accessToken ? (item.isLiked ? '/static/images/icon/like-active.png' : '/static/images/icon/like.png') : '/static/images/icon/like.png'" 
                class="icon" 
              />
              <text>{{ item.likeCount }}</text>
            </view>
            <view class="comment" @tap="showCommentModal(item)">
              <image src="@/static/images/icon/comment.png" class="icon" />
              <text>{{ item.commentCount }}</text>
            </view>
          </view>
        </view>

        <!-- 评论区 -->
        <view v-if="item.showComments" class="comment-list">
          <view v-for="(comment, commentIndex) in item.comments" :key="commentIndex" class="comment-item">
            <image :src="comment.avatar" class="comment-avatar" />
            <text class="comment-user">{{ comment.username }}：</text>
            <text class="comment-content">{{ comment.content }}</text>
          </view>
          <!-- 评论输入框 -->
          <view class="comment-input-area">
            <input 
              v-model="item.commentText" 
              class="comment-input" 
              placeholder="说点什么..." 
              @confirm="handleComment(item)"
            />
            <button class="comment-btn" @tap="handleComment(item)">发送</button>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      <view v-if="!hasMore && contentList.length > 0" class="no-more">
        <text>没有更多内容了</text>
      </view>
    </view>

    <!-- 发布模态框 -->
    <view v-if="showPublish" class="publish-modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="title">发布内容</text>
          <text class="close" @tap="closePublishModal">×</text>
        </view>
        <view class="modal-body">
          <textarea 
            v-model="contentText" 
            placeholder="分享你的养宠心得..." 
            class="content-input"
          />
          
          <!-- 只保留 MediaUpload 组件 -->
          <view class="media-section">
            <MediaUpload
              ref="mediaUploadRef"
              v-model="mediaUrl"
              v-model:mediaType="mediaType"
              :maxSize="10"
              :token="accessToken"
              @update:modelValue="handleMediaUrlUpdate"
              @update:mediaType="handleMediaTypeUpdate"
            />
          </view>

          <!-- 话题输入区域 -->
          <view class="topic-input">
            <input 
              v-model="topicInputValue"
              placeholder="输入#号选择话题" 
              class="topic-input-field"
              @input="handleTopicInput"
            />
          </view>

          <!-- 发布按钮 -->
          <button class="publish-submit-btn" @tap="handlePublish">发布</button>

          <!-- 话题选择弹窗 -->
          <view v-if="showTopicList" class="topic-popup">
            <view class="topic-popup-mask" @tap="showTopicList = false"></view>
            <view class="topic-popup-content">
              <view class="topic-popup-header">
                <text class="topic-popup-title">选择话题</text>
                <text class="topic-popup-close" @tap="showTopicList = false">×</text>
              </view>
              <scroll-view 
                scroll-y 
                class="topic-popup-list"
              >
                <view 
                  v-for="topic in filteredTopics" 
                  :key="topic.id" 
                  class="topic-popup-item"
                  @tap="selectTopic(topic)"
                >
                  <view class="topic-popup-item-title">#{{ topic.title }}</view>
                  <view class="topic-popup-item-desc">{{ topic.description }}</view>
                </view>
                <view v-if="filteredTopics.length === 0" class="topic-popup-empty">
                  暂无相关话题
                </view>
              </scroll-view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import MediaUpload from './components/MediaUpload.vue'

const accessToken = ref(uni.getStorageSync('accessToken'))
const mediaUrl = ref('')
const mediaType = ref('')
const mediaUploadRef = ref(null)

// 分页相关状态
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)

// 内容列表
const contentList = ref([])

// 添加当前用户信息
const currentUser = ref(null)

const userMap = ref({}) // userId => 用户信息

// 添加话题相关的状态
const topicList = ref([]) // 话题列表
const showTopicList = ref(false) // 控制话题列表显示
const filteredTopics = ref([]) // 过滤后的话题列表
const topicInputValue = ref('') // 话题输入值

// 添加选中的话题ID状态
const selectedTopicId = ref('')

// 获取帖子列表
const getPostList = async (isLoadMore = false) => {
  if (loading.value) return

  loading.value = true
  try {
    const token = uni.getStorageSync('accessToken')
    const { data } = await http.request({
      url: '/p/social/post/page',
      method: 'GET',
      header: token ? { 'Authorization': token } : {},
      data: {
        current: pageNum.value,
        size: pageSize.value
      }
    })

    const { records = [], total: totalCount = 0 } = data || {}
    
    // 处理所有帖子
    const allPosts = []
    records.forEach(topic => {
      if (topic.posts && topic.posts.length > 0) {
        topic.posts.forEach(post => {
          if (post.status === 'approved') {
            post.topicInfo = {
              topicId: topic.topicId,
              title: topic.title
            }
            allPosts.push(post)
          }
        })
      }
    })

    // 按创建时间排序
    allPosts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    
    // 去重
    const uniquePosts = allPosts.filter((post, index, self) =>
      index === self.findIndex((p) => p.postId === post.postId)
    )
    
    // 使用Promise.all处理异步格式化
    const formattedPosts = await Promise.all(uniquePosts.map(formatPost))
    
    // 新增：为每个帖子获取评论总数
    await Promise.all(formattedPosts.map(async (item) => {
      try {
        const res = await http.request({
          url: `/p/social/post/${item.postId}/comment`,
          method: 'GET',
        })
        item.commentCount = Array.isArray(res.data) ? res.data.length : 0
      } catch (e) {
        item.commentCount = 0
      }
    }))
    
    if (isLoadMore) {
      contentList.value = [...contentList.value, ...formattedPosts]
    } else {
      contentList.value = formattedPosts
    }

    total.value = totalCount
    hasMore.value = contentList.value.length < totalCount
    if (hasMore.value) {
      pageNum.value++
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    if (error.statusCode === 401) {
      uni.navigateTo({
        url: '/pages/accountLogin/accountLogin'
      })
      return
    }
    
    uni.showToast({
      title: '获取帖子失败',
      icon: 'none'
    })
    
    if (!isLoadMore) {
      contentList.value = []
      total.value = 0
      hasMore.value = false
    }
  } finally {
    loading.value = false
  }
}

// 修改帖子格式化函数
function formatPost(post) {
  const user = userMap.value[post.userId] || {}
  console.log('格式化帖子数据:', post)
  
  let actualType = post.type || 'text'
  if (post.mediaUrl) {
    if (isImage(post.mediaUrl)) {
      actualType = 'image'
    } else if (isVideo(post.mediaUrl)) {
      actualType = 'video'
    }
  }

  const formattedPost = {
    id: Number(post.postId || 0),
    postId: Number(post.postId || 0),
    userId: post.userId || '',
    username: user.nickName || post.nickName || '匿名用户',
    userAvatar: user.pic || post.pic || '/static/images/icon/head04.png',
    content: post.content || '',
    mediaUrl: post.mediaUrl || '',
    type: actualType,
    topic: post.topicInfo ? `#${post.topicInfo.title}` : '',
    topicId: post.topicInfo?.topicId,
    likeCount: Number(post.likeCount || 0),
    isLiked: Boolean(post.isLiked || false),
    commentCount: Number(post.commentCount || 0),
    showComments: false,
    comments: [],
    commentText: '',
    createTime: post.createdAt || new Date().toISOString()
  }

  console.log('格式化后的帖子:', formattedPost)
  return formattedPost
}

// 下拉刷新
const onPullDownRefresh = async () => {
  pageNum.value = 1
  hasMore.value = true
  await getPostList(false) // 重新加载第一页
  uni.stopPullDownRefresh()
}

// 上拉加载更多
const onReachBottom = () => {
  if (hasMore.value && !loading.value) {
    getPostList(true) // 加载下一页
  }
}

// 修改 onShow 生命周期
onShow(() => {
  loadCommunityData()
  getAllUsers()
})

// 简化数据加载函数
const loadCommunityData = async () => {
  try {
    uni.showLoading()
    const token = uni.getStorageSync('accessToken')
    
    // 获取用户信息
    if (token) {
      const { data: userInfo } = await http.request({
        url: '/p/user/userInfo',
        method: 'GET',
        header: {
          'Authorization': token
        }
      })

      if (userInfo) {
      currentUser.value = {
          id: userInfo.userId,
          userId: userInfo.userId,
          nickName: userInfo.nickName,
          pic: userInfo.pic || '/static/images/icon/head04.png'
        }
        accessToken.value = token
      }
    }

    // 获取帖子列表
    await getPostList()
    uni.hideLoading()
  } catch (error) {
    console.error('加载社区数据失败:', error)
    uni.hideLoading()
    }
  }

// 发布相关状态
const showPublish = ref(false)
const contentText = ref('')
const publishTopic = ref('')
const selectedImages = ref([])
const selectedVideo = ref('')

// 修改发布模态框显示逻辑
const showPublishModal = () => {
  showPublish.value = true
  accessToken.value = uni.getStorageSync('accessToken')
}

// 关闭发布模态框
const closePublishModal = () => {
  console.log('关闭发布模态框')
  showPublish.value = false
  contentText.value = ''
  publishTopic.value = ''
  selectedImages.value = []
  selectedVideo.value = ''
  mediaUploadRef.value?.clearUpload()
}

// 修改发布内容的处理函数
const handlePublish = async () => {
  if (!contentText.value.trim()) {
    uni.showToast({
      title: '请输入内容',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({
      title: '发布中...',
      mask: true
    })

    // 处理话题
    let finalTopic = publishTopic.value
    let finalTopicId = selectedTopicId.value
    
    // 如果用户输入了新话题（没有选择现有话题）
    if (topicInputValue.value && !topicInputValue.value.includes('#')) {
      try {
        // 先创建新话题
        const newTopic = {
          title: topicInputValue.value.trim(),
          description: `关于${topicInputValue.value}的讨论`
        }
        
        const { data: createdTopic } = await http.request({
          url: '/p/social/post/topics',
          method: 'POST',
          header: {
            'Authorization': accessToken.value
          },
          data: newTopic
        })

        if (!createdTopic || !createdTopic.topicId) {
          throw new Error('创建话题失败：未获取到话题ID')
        }

        // 使用新创建的话题信息
        finalTopic = `#${newTopic.title}`
        finalTopicId = createdTopic.topicId
        
        // 刷新话题列表
        await getTopics()
      } catch (error) {
        console.error('创建话题失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '创建话题失败，请重试',
          icon: 'none'
        })
        return
      }
    }

    // 准备发布数据
    const postData = {
      content: contentText.value,
      type: mediaType.value || 'text',
      mediaUrl: mediaUrl.value || '',
      topic: finalTopic || '',
      topicId: finalTopicId || ''
    }

    console.log('准备发送的数据:', postData)

    // 发送发布请求
    const response = await http.request({
      url: '/p/social/post',
      method: 'POST',
      header: {
        'Authorization': accessToken.value
      },
      data: postData
    })

    console.log('发布响应:', response)

    // 清空表单
    contentText.value = ''
    publishTopic.value = ''
    topicInputValue.value = ''
    mediaUrl.value = ''
    mediaType.value = ''
    selectedTopicId.value = ''
    mediaUploadRef.value?.clearUpload()
    
    uni.hideLoading()
    
    uni.showToast({
      title: '发布成功',
      icon: 'success'
    })
    
    showPublish.value = false
    
    // 刷新列表
    pageNum.value = 1
    hasMore.value = true
    await getPostList()
  } catch (error) {
    uni.hideLoading()
    console.error('发布失败:', error)
    uni.showToast({
      title: '发布失败，请重试',
      icon: 'none'
    })
  }
}

// 显示评论
const showCommentModal = async (item) => {
  // 如果评论区已经显示，则关闭它
  if (item.showComments) {
    item.showComments = false
    return
  }
  
  try {
    const postId = Number(item.postId)
    console.log('获取评论列表，帖子ID:', postId)

    const { data } = await http.request({
      url: `/p/social/post/${postId}/comment`,
      method: 'GET',
      header: {
        'Authorization': accessToken.value
      }
    })
    
    console.log('获取到的评论数据:', data)
    
    // 确保 comments 始终是数组
    item.comments = Array.isArray(data) ? data.map(comment => ({
      id: comment.id,
      userId: comment.userId,
      username: userMap.value[comment.userId]?.nickName || comment.nickName || '匿名用户',
      avatar: userMap.value[comment.userId]?.pic || '/static/images/icon/head04.png',
      content: comment.content,
      createTime: comment.createTime
    })) : []
    
    // 获取评论总数
    item.commentCount = Array.isArray(data) ? data.length : 0
    
    // 无论是否有评论，都显示评论区
    item.showComments = true
    
    // 如果评论为空，可以显示一个提示
    if (item.comments.length === 0) {
      console.log('该帖子暂无评论')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    // 即使获取评论失败，也显示评论区，但显示错误提示
    item.comments = []
    item.showComments = true
    item.commentCount = 0
    uni.showToast({
      title: '获取评论失败',
      icon: 'none'
    })
  }
}

// 预览图片
const previewImage = (images, current) => {
  if (!images || images.length === 0) return
  uni.previewImage({
    urls: images,
    current: images[current] || images[0],
    fail: (err) => {
      console.error('预览图片失败:', err)
      uni.showToast({
        title: '预览图片失败',
        icon: 'none'
      })
    }
  })
}

// 发送评论
const handleComment = async (item) => {
  // 添加调试日志
  console.log('当前帖子信息:', {
    postId: item.postId,
    type: typeof item.postId,
    content: item.content,
    commentText: item.commentText
  })

  if (!item.commentText?.trim()) {
    uni.showToast({
      title: '请输入评论内容',
      icon: 'none'
    })
    return
  }

  if (!item.postId) {
    console.error('帖子数据:', item)
    uni.showToast({
      title: '帖子ID不存在，请刷新重试',
      icon: 'none'
    })
    return
  }

  try {
    // 确保使用数字类型的postId
    const postId = Number(item.postId)
    await http.request({
      url: `/p/social/post/${postId}/comment`,
      method: 'POST',
      data: {
        content: item.commentText,
        parentId: null
      }
    })

    // 重新获取评论列表
    const { data } = await http.request({
      url: `/p/social/post/${postId}/comment`,
      method: 'GET'
    })
    
    // 更新评论列表
    item.comments = data.map(comment => ({
      id: comment.id,
      userId: comment.userId,
      username: comment.nickName || '匿名用户',
      content: comment.content,
      createTime: comment.createTime
    }))
    
    item.commentCount = item.comments.length
    item.commentText = '' // 清空输入框

    uni.showToast({
      title: '评论成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('评论失败:', error)
    uni.showToast({
      title: `评论失败: ${error.message || '未知错误'}`,
      icon: 'none'
    })
  }
}

// 在 setup 中添加登录事件监听
onMounted(() => {
  // 监听登录成功事件
  uni.$on('loginSuccess', async ({ token, userInfo }) => {
    console.log('收到登录成功事件:', { token, userInfo })
    
    // 更新 token
    accessToken.value = token
    
    // 更新用户信息
    currentUser.value = {
      id: userInfo.userId,
      userId: userInfo.userId,
      nickName: userInfo.nickName,
      pic: userInfo.pic || '/static/images/icon/head04.png'
    }
    
    // 刷新帖子列表
    pageNum.value = 1
    hasMore.value = true
    await getPostList()
  })

  // 在组件挂载时获取话题列表
  getTopics()
})

// 在组件卸载时移除事件监听
onUnmounted(() => {
  uni.$off('loginSuccess')
})

// 在 script setup 部分添加以下方法
const handleMediaUrlUpdate = (url) => {
  console.log('媒体URL更新:', url)
  mediaUrl.value = url
}

const handleMediaTypeUpdate = (type) => {
  console.log('媒体类型更新:', type)
  mediaType.value = type
}

// 在 script setup 中添加这些工具函数
const isImage = (url) => {
  return url && /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
}

const isVideo = (url) => {
  return url && /\.(mp4|webm|ogg|mov)$/i.test(url)
}

const getAllUsers = async () => {
  try {
    const { data } = await http.request({
      url: '/p/user/userInfoAll',
      method: 'GET'
    })
    // 假设 data 是用户数组
    const map = {}
    if (Array.isArray(data)) {
      data.forEach(user => {
        map[user.userId] = user
      })
    }
    userMap.value = map
  } catch (e) {
    console.error('获取所有用户信息失败', e)
  }
}

// 获取话题列表
const getTopics = async () => {
  try {
    const { data } = await http.request({
      url: '/p/social/post/topics',
      method: 'GET'
    })
    
    if (Array.isArray(data)) {
      topicList.value = data.map(topic => ({
        id: topic.topicId,
        title: topic.title,
        description: topic.description
      }))
    }
  } catch (error) {
    console.error('获取话题列表失败:', error)
  }
}

// 修改监听话题输入的函数
const handleTopicInput = async (e) => {
  const value = e.detail.value || ''
  topicInputValue.value = value
  
  // 检查是否输入了"# "模式
  if (value === '# ') {
    // 清空输入框，准备让用户输入新话题
    topicInputValue.value = ''
    uni.showModal({
      title: '创建新话题',
      content: '请输入新话题名称',
      editable: true,
      placeholderText: '例如：养狗日常',
      success: async (res) => {
        if (res.confirm && res.content) {
          try {
            uni.showLoading({
              title: '创建话题中...',
              mask: true
            })

            // 创建新话题
            const newTopic = {
              title: res.content.trim(),
              description: `关于${res.content}的讨论`
            }
            
            await http.request({
              url: '/p/social/post/topics',
              method: 'POST',
              header: {
                'Authorization': accessToken.value
              },
              data: newTopic
            })

            // 更新输入框的值
            topicInputValue.value = `#${newTopic.title} `
            publishTopic.value = topicInputValue.value

            // 刷新话题列表
            await getTopics()

            uni.hideLoading()
            uni.showToast({
              title: '话题创建成功',
              icon: 'success'
            })
          } catch (error) {
            uni.hideLoading()
            console.error('创建话题失败:', error)
            uni.showToast({
              title: '创建话题失败',
              icon: 'none'
            })
          }
        }
      }
    })
    return
  }
  
  // 原有的话题选择逻辑
  if (value.includes('#')) {
    const searchText = value.split('#').pop() || ''
    if (searchText === '') {
      filteredTopics.value = topicList.value
      showTopicList.value = true
    } else {
      filteredTopics.value = topicList.value.filter(topic => 
        topic.title.toLowerCase().includes(searchText.toLowerCase())
      )
      showTopicList.value = true
    }
  } else {
    showTopicList.value = false
  }
}

// 修改话题选择函数
const selectTopic = (topic) => {
  const currentValue = topicInputValue.value
  const lastHashIndex = currentValue.lastIndexOf('#')
  
  if (lastHashIndex !== -1) {
    topicInputValue.value = currentValue.substring(0, lastHashIndex) + '#' + topic.title + ' '
  } else {
    topicInputValue.value = '#' + topic.title + ' '
  }
  
  publishTopic.value = topicInputValue.value.trim()
  // 保存选中的话题ID
  selectedTopicId.value = topic.id
  showTopicList.value = false
}

// 确保在组件挂载时获取话题列表
onMounted(async () => {
  // 获取话题列表
  await getTopics()
  console.log('获取到的话题列表:', topicList.value)
  
  // ... 其他已有的 onMounted 代码 ...
})

// 修改点赞处理函数
const handleLike = async (item) => {
  try {
    uni.showLoading({ mask: true })
    
    // 发送点赞请求，postId作为路径参数，like作为查询参数
    await http.request({
      url: `/p/social/post/${item.postId}/like?like=${!item.isLiked}`,
      method: 'POST',
      header: {
        'Authorization': accessToken.value
      }
    })
    
    // 更新点赞状态
    item.isLiked = !item.isLiked
    
    // 更新点赞数，确保是数字运算
    item.likeCount = Number(item.likeCount || 0) // 确保当前值是数字
    item.likeCount = item.isLiked ? (item.likeCount + 1) : (item.likeCount - 1)
    
    // 添加点赞动画效果
    item.likeAnimating = true
    setTimeout(() => {
      item.likeAnimating = false
    }, 300)
    
    uni.hideLoading()

    // 显示操作结果
    uni.showToast({
      title: item.isLiked ? '点赞成功' : '已取消点赞',
      icon: 'success'
    })
  } catch (error) {
    uni.hideLoading()
    console.error('点赞操作失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    })
  }
}

const getGuessYouLike = async () => {
  const token = uni.getStorageSync('accessToken')
  const userInfo = uni.getStorageSync('userInfo')
  
  console.log('猜你喜欢参数:', {
    userInfo,
    token
  })
  
  // 检查登录状态
  if (!token || !userInfo) {
    console.log('用户未登录，无法获取推荐')
    guessYouLike.value = []
    return
  }

  try {
    // 添加详细的请求日志
    console.log('开始请求推荐接口:', `/p/recommend/user/${userInfo.userId}`)
    
    const { data: response } = await http.request({
      url: `/p/recommend/user/${userInfo.userId}`,
      method: 'GET',
      header: {
        'Authorization': token
      }
    })
    
    console.log('推荐接口完整响应:', response)
    
    // 检查响应结构
    if (response && response.success) {
      // 根据新的接口响应格式，data 字段包含推荐商品数组
      guessYouLike.value = response.data || []
      console.log('成功设置推荐商品列表，数量:', guessYouLike.value.length)
    } else {
      console.error('推荐接口返回格式异常:', response)
      guessYouLike.value = []
    }
    
  } catch (err) {
    console.error('获取推荐商品失败:', {
      error: err,
      message: err.message,
      status: err.statusCode
    })
    
    // 如果是 401 未授权，可能需要重新登录
    if (err.statusCode === 401) {
      console.log('token 已过期，需要重新登录')
      uni.navigateTo({
        url: '/pages/accountLogin/accountLogin'
      })
    }
    
    guessYouLike.value = []
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.publish-btn {
  position: fixed;
  right: 40rpx;
  bottom: 100rpx;
  width: 100rpx;
  height: 100rpx;
  background-color: #1b7dec;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);

  &:active {
    opacity: 0.8;
  }

  .publish-icon {
    width: 50rpx;
    height: 50rpx;
  }
}

.content-list {
  margin-top: 20rpx;
}

.content-item {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 20rpx;
  }

  .username {
    font-size: 28rpx;
    font-weight: bold;
  }
}

.content-main {
  margin-bottom: 20rpx;

  .content-text {
    font-size: 28rpx;
    line-height: 1.5;
  }

  .topics-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10rpx;
    margin-top: 10rpx;
  }

  .topic-tag {
    display: inline-block;
    color: #1b7dec; // 使用蓝色
    font-size: 24rpx;
    padding: 4rpx 16rpx;
    border-radius: 16rpx;
    background-color: rgba(27, 125, 236, 0.1); // 淡蓝色背景
    
    &:active {
      opacity: 0.8;
    }
  }

  .image-list {
    display: flex;
    flex-wrap: wrap;
    margin-top: 20rpx;

    .content-image {
      width: 200rpx;
      height: 200rpx;
      margin-right: 10rpx;
      margin-bottom: 10rpx;
      border-radius: 10rpx;
    }
  }

  .content-video {
    width: 100%;
    height: 400rpx;
    margin-top: 20rpx;
    border-radius: 10rpx;
  }
}

.content-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .interaction {
    display: flex;
    align-items: center;

    .like, .comment {
      display: flex;
      align-items: center;
      margin-left: 30rpx;
      cursor: pointer;

      .icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 10rpx;
        transition: all 0.3s ease;
      }

      text {
        font-size: 24rpx;
        color: #666;
      }
    }

    .like {
      &.like-animating {
        animation: likeScale 0.3s ease;
      }
    }
  }
}

.comment-list {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;

  .comment-item {
    margin-bottom: 10rpx;
    font-size: 26rpx;

    .comment-avatar {
      width: 40rpx;
      height: 40rpx;
      border-radius: 50%;
      margin-right: 10rpx;
      vertical-align: middle;
    }

    .comment-user {
      color: #1b7dec;
      font-weight: bold;
    }
  }
}

.comment-input-area {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;

  .comment-input {
    flex: 1;
    height: 60rpx;
    background-color: #fff;
    border-radius: 30rpx;
    padding: 0 20rpx;
    font-size: 26rpx;
  }

  .comment-btn {
    margin-left: 20rpx;
    height: 60rpx;
    line-height: 60rpx;
    padding: 0 30rpx;
    background-color: #1b7dec;
    color: #fff;
    border-radius: 30rpx;
    font-size: 26rpx;
  }
}

.publish-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1002;

  .modal-content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    padding: 30rpx;
    transform: translateY(0);
    transition: transform 0.3s ease;
  }

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .close {
      font-size: 40rpx;
      color: #999;
    }
  }

  .modal-body {
    padding: 20rpx;
    
    .content-input {
      width: 100%;
      height: 200rpx;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;
      font-size: 28rpx;
    }

    .media-section {
      margin: 20rpx 0;
      
      .media-options {
        display: flex;
        gap: 30rpx;
        margin-bottom: 20rpx;
        
        .media-option {
          display: flex;
          align-items: center;
          gap: 8rpx;
          padding: 10rpx 20rpx;
          background-color: #f5f5f5;
          border-radius: 30rpx;
          
          .media-icon {
            width: 40rpx;
            height: 40rpx;
          }
          
          text {
            font-size: 26rpx;
            color: #666;
          }
        }
      }
    }

    .topic-input {
      margin: 20rpx 0;
      
      .topic-input-field {
        width: 100%;
        height: 80rpx;
        background-color: #fff2f5;
        border-radius: 20rpx;
        padding: 0 20rpx;
        border: 2rpx solid #ffb6c1;
        font-size: 26rpx;
        
        &::placeholder {
          color: #ffb6c1;
        }
      }
    }

    .publish-submit-btn {
      width: 100%;
      height: 88rpx;
      background-color: #1b7dec;
      color: #fff;
      border-radius: 44rpx;
      font-size: 32rpx;
      font-weight: bold;
      margin-top: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      &:active {
        opacity: 0.9;
      }
    }
  }
}

.loading, .no-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

// 修改话题输入框样式
.topic-input {
  margin-top: 24rpx;
  
  &-field {
    width: 100%;
    height: 80rpx;
    background-color: #fff;
    border-radius: 40rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
    border: 2rpx solid #eee;
    
    &::placeholder {
      color: #999;
    }
  }
}

.topic-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1003;

  .topic-popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .topic-popup-content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    padding: 30rpx;
    transform: translateY(0);
    transition: transform 0.3s ease;

    .topic-popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;

      .topic-popup-title {
        font-size: 32rpx;
        font-weight: bold;
      }

      .topic-popup-close {
        font-size: 40rpx;
        color: #999;
      }
    }

    .topic-popup-list {
      max-height: 400rpx;
      overflow-y: auto;

      .topic-popup-item {
        padding: 10rpx 20rpx;
        border-bottom: 1rpx solid #eee;
        font-size: 28rpx;

        &:last-child {
          border-bottom: none;
        }

        .topic-popup-item-title {
          font-size: 28rpx;
          font-weight: bold;
        }

        .topic-popup-item-desc {
          font-size: 26rpx;
          color: #666;
        }
      }

      .topic-popup-empty {
        text-align: center;
        padding: 20rpx 0;
        color: #999;
        font-size: 24rpx;
      }
    }
  }
}

@keyframes likeScale {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}
</style>    